<template>
  <el-page-header class="head" :icon="null" title="云手机平台">
    <template #content>
      <div><span>云手机列表</span></div>
    </template>
    <template #extra>
      <div>
        <el-button v-if="isMobile" @click="changeDrawer(true)" type="primary">
          查看
        </el-button>
        <el-button @click="exit" type="danger">退出</el-button>
      </div>
    </template>
  </el-page-header>
  <div class="wallpaper" v-loading="loading">
    <div v-if="!isMobile" class="search-container">
      <el-form label-width="auto" :model="searchForm">
        <el-form-item label="Region" prop="region">
          <el-select
            class="el-form-select"
            v-model="searchForm.region"
            @change="regionChange"
            placeholder="请选择region"
          >
            <el-option
              class="el-form-select"
              v-for="item in regionOptions"
              :key="item.id"
              :label="item.label"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="ServerId" prop="server_id">
          <el-input
            v-model="searchForm.server_id"
            class="el-form-input"
            placeholder="请先输入serverId"
            clearable
          >
          </el-input>
        </el-form-item>
        <el-button @click="queryPhoneListClick" type="primary" :icon="Search" />
        <el-button @click="refresh" type="primary" :icon="Refresh" />
      </el-form>
    </div>
    <el-drawer
      v-else
      v-model="drawerVisible"
      :closeOnClickModal="false"
      :closeOnPressEscape="false"
      :showClose="false"
      class="mobile-drawer"
    >
      <template #header>
        <h4>过滤条件</h4>
      </template>
      <template #default>
        <el-form label-width="auto" :model="searchForm">
          <el-form-item label="Region" prop="region">
            <el-select
              class="el-form-select"
              v-model="searchForm.region"
              @change="regionChange"
              placeholder="请选择region"
            >
              <el-option
                class="el-form-select"
                v-for="item in regionOptions"
                :key="item.id"
                :label="item.label"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="ServerId" prop="server_id">
            <el-input
              v-model="searchForm.server_id"
              class="el-form-input"
              placeholder="请先输入serverId"
              clearable
            >
            </el-input>
          </el-form-item>
          <el-form-item
            v-if="paginationOptions.list.length"
            label="页码"
            prop="paginationOptions"
          >
            <el-select
              class="el-form-select"
              v-model="pageInfo.currentPage"
              @change="mobileCurrentPageChange"
            >
              <el-option
                class="el-form-select"
                v-for="item in paginationOptions.list"
                :key="item.id"
                :label="item.id"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <div style="display: flex">
          <el-button @click="changeDrawer(false)">取消</el-button>
          <el-button type="primary" @click="queryPhoneListClick">
            确认
          </el-button>
        </div>
      </template>
    </el-drawer>
    <div class="phone-container">
      <el-scrollbar :key="connectPhones.list.length" ref="scrollbarRef">
        <div v-if="pageInfo.total" class="phone-list">
          <template
            v-for="(item, index) in connectPhones.list"
            :key="item.phone_id"
          >
            <div class="phone-item">
              <phoneViewComp
                :class="['phone-item-container']"
                :connectInfo="item"
              />
              <div>{{ getPhoneName(connectPhones.list, index) }}</div>
            </div>
          </template>
        </div>
        <el-result v-else title="暂无数据"> </el-result>
      </el-scrollbar>
      <el-divider style="margin: 12px 0 8px 0" />
      <el-pagination
        class="pagination"
        v-model:current-page="pageInfo.currentPage"
        v-model:page-size="pageInfo.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageInfo.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>
<script lang="ts">
import {
  iamLogin,
  queryPhoneList,
  queryPhonesConnectInfo,
} from '@/request/request';
import { reactive, ref } from 'vue';
import { Search, Refresh } from '@element-plus/icons-vue';
import phoneViewComp from '../components/phoneViewComp.vue';
import { ElMessage } from 'element-plus';
export default {
  setup() {
    const pageInfo = reactive({
      pageSize: 10,
      currentPage: 1,
      total: 0,
    });
    const isMobile = /(iPhone|iPad|iPod|iOS|Android)/i.test(
      navigator.userAgent,
    );
    const phoneList = reactive({ list: [] });
    const connectPhones = reactive({ list: [] });
    const searchForm = reactive({
      region: localStorage.getItem('region'),
      server_id: '',
    });
    const paginationOptions = reactive({ list: [] });
    const regionOptions = reactive([
      { id: 'cn-north-4', label: '华北-北京四' },
      { id: 'cn-east-2', label: '华东-上海二' },
      { id: 'cn-east-3', label: '华东-上海一' },
      { id: 'cn-south-1', label: '华南-广州' },
      { id: 'cn-southwest-2', label: '西南-贵阳一' },
      { id: 'ap-southeast-3', label: '亚太-新加坡' },
      { id: 'ap-southeast-1', label: '中国-香港' },
      { id: 'ru-northwest-2', label: '俄罗斯-莫斯科二' },
      { id: 'cn-north-9', label: '华北-乌兰察布一' },
    ]);
    const loading = ref(false);
    const drawerVisible = ref(false);
    return {
      loading,
      searchForm,
      regionOptions,
      paginationOptions,
      pageInfo,
      phoneList,
      isMobile,
      connectPhones,
      drawerVisible,
      Search,
      Refresh,
    };
  },
  components: {
    phoneViewComp,
  },
  created() {},
  methods: {
    queryPhoneListClick() {
      if (this.searchForm.server_id && this.searchForm.region) {
        this.queryPhoneList();
        if (this.isMobile) {
          this.drawerVisible = false;
        }
      } else {
        ElMessage({
          message: '请先补全Region或ServerId',
          type: 'warning',
        });
      }
    },
    async queryPhoneList() {
      try {
        this.loading = true;
        const project_id = JSON.parse(localStorage.getItem('project_id'))[
          this.searchForm.region
        ];
        const phoneRes = await queryPhoneList({
          project_id,
          offset: (this.pageInfo.currentPage - 1) * this.pageInfo.pageSize,
          limit: this.pageInfo.pageSize,
          type: 0,
          server_id: this.searchForm.server_id,
        });
        this.pageInfo.total = phoneRes.data.count;
        this.phoneList.list = phoneRes.data.phones;
        let paginationOptions = [];
        for (
          let i = 1;
          i <= Math.ceil(this.pageInfo.total / this.pageInfo.pageSize);
          i++
        ) {
          paginationOptions.push({ id: i });
        }
        this.paginationOptions.list = paginationOptions;
        this.queryPhonesConnectInfo(project_id);
      } catch (e) {
        this.pageInfo.total = 0;
        this.pageInfo.currentPage = 1;
        this.phoneList.list = [];
        this.paginationOptions.list = [];
      }
    },
    async queryPhonesConnectInfo(project_id) {
      try {
        this.loading = true;
        if (!this.phoneList.list.length) {
          return;
        }
        const connectRes = await queryPhonesConnectInfo({
          project_id,
          phone_ids: this.phoneList.list.map(item => item.phone_id),
          client_type: 'H5_PC',
        });
        const connectPhones = [...connectRes.data.connect_infos] || [];
        const disconnectPhones = connectRes.data.errors || [];
        this.connectPhones.list = [...connectPhones, ...disconnectPhones];
      } catch (e) {
        this.connectPhones.list = [];
      } finally {
        this.loading = false;
      }
    },

    refresh() {
      this.connectPhones.list = [];
      this.queryPhonesConnectInfo(
        JSON.parse(localStorage.getItem('project_id'))[this.searchForm.region],
      );
    },

    async regionChange() {
      try {
        this.loading = true;
        localStorage.setItem('region', this.searchForm.region);
        const res: any = await iamLogin(
          JSON.parse(localStorage.getItem('user_info')),
        );
        const region = localStorage.getItem('region');
        localStorage.setItem('token', res.headers['x-subject-token']);
        localStorage.setItem(
          'project_id',
          JSON.stringify({
            [region]: res.data.token.project.id,
          }),
        );
        this.queryPhoneList();
      } finally {
        this.loading = false;
      }
    },
    handleSizeChange(size) {
      this.pageInfo.pageSize = size;
      this.queryPhoneList();
    },

    handleCurrentChange(currentPage) {
      this.pageInfo.currentPage = currentPage;
      this.queryPhoneList();
    },

    mobileCurrentPageChange(currentPage) {
      this.pageInfo.currentPage = currentPage;
    },

    getPhoneName(connectPhones, index) {
      const item = this.phoneList.list.find(
        item => item.phone_id === connectPhones[index].phone_id,
      );
      return item?.phone_name || '';
    },

    changeDrawer(drawerVisible) {
      this.drawerVisible = drawerVisible;
    },

    exit() {
      this.connectPhones.list = [];
      this.$router.push('/login');
    },
  },
};
</script>
<style scoped lang="less">
.head {
  padding: 20px;
  :deep(.el-page-header__title) {
    color: var(--el-text-color-primary);
    font-size: 18px;
  }
}
.wallpaper {
  height: calc(100vh - 72px);
  width: 100vw;
  display: flex;
  flex-direction: column;
  background: radial-gradient(
    circle at 5px 5px,
    var(--el-fill-color-dark) 2px,
    #f2f6fc 0
  );
  background-size: 25px 25px;
}

.search-container {
  display: flex;
  align-items: center;
  margin: 1rem 0.5rem 0 0.5rem;
  padding: 1rem;
  width: calc(100% - 1rem);
  height: 70px;
  background-color: #fff;
  border: 1px solid var(--el-border-color);
  border-radius: 10px;
  :deep(.el-form) {
    display: flex;
    .el-form-select {
      width: 240px;
    }
    .el-form-input {
      width: 340px;
    }
    .el-form-item--default {
      margin-right: 20px;
      margin-bottom: 0;
    }
  }
}
.phone-container {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
  padding: 1rem;
  min-height: 500px;
  margin: 0.5rem;
  width: calc(100% - 1rem);
  background-color: #fff;
  border: 1px solid var(--el-border-color);
  border-radius: 10px;
}
.phone-list {
  display: flex;
  flex-wrap: wrap;
  .phone-item {
    display: flex;
    flex-direction: column;
    align-items: center;
  }
}
.phone-item-container {
  overflow: hidden;
  margin: 1rem 2rem;
  box-shadow: 0px 6px 16px 2px rgba(0, 0, 0, 0.04),
    0px 4px 10px rgba(0, 0, 0, 0.08);
  border: 1px solid var(--el-border-color);
  border-radius: 12px;
  width: 22.5rem;
  height: 40rem;
}

:deep(.mobile-drawer) {
  width: 80% !important;
}

@media screen and (max-width: 720px) {
  .pagination {
    display: none;
  }
  .phone-container {
    height: 100%;
  }
  .phone-item-container {
    margin: 0.3rem 0.6rem;
    width: 13rem;
    height: 22rem;
    box-shadow: 0px 3px 8px 1px rgba(0, 0, 0, 0.04),
      0px 2px 5px rgba(0, 0, 0, 0.08);
    border-radius: 8px;
  }
}
</style>
